package com.situ.stmall.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.ibatis.annotations.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.situ.stmall.entity.Goods;
import com.situ.stmall.entity.Order;
import com.situ.stmall.entity.OrderDetails;
import com.situ.stmall.entity.Shopcart;
import com.situ.stmall.entity.User;
import com.situ.stmall.mapper.GoodsMapper;
import com.situ.stmall.mapper.OrderDetailsMapper;
import com.situ.stmall.mapper.OrderMapper;
import com.situ.stmall.mapper.ShopcartMapper;
import com.situ.stmall.mapper.UserMapper;
import com.situ.stmall.service.OrderService;
import com.situ.stmall.util.MD5Util;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private ShopcartMapper shopcartMapper;
	@Autowired
	private OrderDetailsMapper orderDetailsMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private UserMapper userMapper;
	
	
	@Override
	@Transactional
	public Order add(Integer userId, Integer[] cartIds) throws Exception {
		//1.判断cartIds的长度
		if (cartIds.length == 0 || cartIds == null) {
			throw new Exception("未发现任何商品");
		}
		
		List<Shopcart> carts = new ArrayList<>();
		
		//查询购物车信息
		for (int i = 0; i < cartIds.length; i++) {
			Shopcart cart = shopcartMapper.selectByPrimaryKey(cartIds[i]);
			
			carts.add(cart);
			
			//查询cart是否存在
			if (cart == null) {
				throw new Exception("购物车信息查询失败");
			}
			//验证cart是不是存在
			if (userId != cart.getUserId()) {
				throw new Exception("购物车用户信息出错");
			}
			//验证库存问题
			if (cart.getCount() > cart.getGoods().getCount()) {
				throw new Exception("购买的商品库存不足，订单生成失败");
			}
			//验证购物车购买数量不能为零
			if (cart.getCount() <= 0) {
				throw new Exception("购买的商品数量不能为零，订单生成失败");
			}
		}
		
		//生成订单对象
		Order order = new Order();
		//UUID
		order.setId(UUID.randomUUID().toString());
		order.setUserId(userId);
		int res = orderMapper.insert(order);
		
		if (res < 0) {
			throw new Exception("订单信息保存失败");
		}
		//遍历cart中的数据生成订单中的详情
		for (int i = 0; i < carts.size(); i++) {
			OrderDetails orderDetails = new OrderDetails();
			orderDetails.setOrderId(order.getId());
			orderDetails.setGoodsId(carts.get(i).getGoodsId());
			orderDetails.setCount(carts.get(i).getCount());
			orderDetails.setPrice(carts.get(i).getGoods().getPrice());
			
			//保存到数据库
			res = orderDetailsMapper.insert(orderDetails);
			if (res <= 0) {
				throw new Exception("订单详情保存失败");
			}
		}
		//清理购物车信息
		for (int i = 0; i < carts.size(); i++) {
			res = shopcartMapper.deleteByPrimaryKey(carts.get(i).getId());
			if (res <= 0) {
				throw new Exception("购物车信息清除失败");
			}
			
			//扣除商品的库存
			Goods goods = carts.get(i).getGoods();
			goods.setCount(goods.getCount() - carts.get(i).getCount());
			
			//写回数据库
			res = goodsMapper.updateByPrimaryKey(goods);
			if (res <= 0) {
				throw new Exception("商品库存扣除失败");
			}
		}
		
		//7.返回Order
		
		return orderMapper.selectByPrimaryKey(order.getId());
	}

	@Override
	public Order getById(String orderId) {
		
		return orderMapper.selectByPrimaryKey(orderId);
	}

	@Override
	public int update(Order order) {
		// TODO Auto-generated method stub
		return orderMapper.updateByPrimaryKey(order);
	}

	
	@Override
	@Transactional
	public int pay(String orderId, String paypwd, Integer userId) throws Exception{
		// 验证支付密码
		User user = userMapper.selectByPrimaryKey(userId);
		if (user.getPaypwd()==null) {
			throw new Exception("未设置支付密码");
		}
		
		if (user.getPaypwd().equals(MD5Util.getMD5(paypwd))) {
			//密码不对
			throw new Exception("密码错误");
		}
		
		//扣款
		Order order = orderMapper.selectByPrimaryKey(orderId);
		BigDecimal sum = new BigDecimal(0);
		
		for (int i = 0; i < order.getOrderDetails().size(); i++) {
			OrderDetails orderDetails = order.getOrderDetails().get(i);
			BigDecimal total = orderDetails.getPrice().multiply(new BigDecimal(orderDetails.getCount()));
			
			sum = sum.add(total);
		}
		if (user.getMoney().compareTo(sum) < 0) {
			throw new Exception("订单余额不足");
		}
		
		user.setMoney(user.getMoney().subtract(sum));
		
		int res = userMapper.updateByPrimaryKey(user);
		if (res <= 0) {
			throw new Exception("订单扣款失败，请联系管理员");//扣款失败
		}
		
		
		//修改订单状态
		if (order.getStatus() != 0) {
			//订单不是未支付状态
			throw new Exception("订单状态错误，无法完成支付");
		}
		order.setStatus(1);//订单已支付
		res = orderMapper.updateByPrimaryKey(order);
		
		if (res <= 0) {
			throw new Exception("订单状态修改失败");//订单状态修改失败
		}
		
		return 1;
	}

	@Override
	public List getByUserId(Integer userId) {
		List orders = orderMapper.selectByUserId(userId);
		return orders;
	}

	@Override
	@Transactional
	public int clean() {
		//清理无效订单
		//时间是半小时之前
		//状态是未支付
		List<Order> orders = orderMapper.selectInvalid();
		
		//清理订单信息
		//删除订单，订单详情，库存复原
		for (Order order : orders) {
			for (OrderDetails detail : order.getOrderDetails()) {
				Goods goods = detail.getGoods();
				goods.setCount(goods.getCount() + detail.getCount());
				goodsMapper.updateByPrimaryKey(goods);
				
				//删除详情
				orderDetailsMapper.deleteByPrimaryKey(detail.getId());
				
			}
			
			//删除当前订单
			orderMapper.deleteByPrimaryKey(order.getId());
		}
		
		
		return 0;
	}

}
